package com.walle.concurrenttest.pattern.readwritelock;

import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangjiapeng
 * @Package com.walle.concurrenttest.pattern.readwritelock
 * @Description: ${todo}
 * @date 2019/2/20 14:15
 */
public class WriteThread implements Runnable {


    private final Random random = new Random();
    private final Data data;
    private final String filter;
    private int index = 0;


    public WriteThread(Data data,String filter) {
        this.data = data;
        this.filter = filter;
    }

    @Override
    public void run() {

        try {
            while (true){
                char c = nextChar();
                data.write(c);
                System.out.println(Thread.currentThread().getName() + " write " + String.valueOf(c));
                Thread.sleep(random.nextInt(3000));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public char nextChar(){
        char c = filter.charAt(index);
        index++;
        if(index >= filter.length()){
            index = 0;
        }
        return  c;
    }
}
